﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace TxtFormat
{
    public partial class TxtFormat : Form
    {
        public TxtFormat()
        {
            InitializeComponent();
        }

        private void TxtFormat_Load(object sender, EventArgs e)
        {
            this.encodeCb.SelectedIndex = 0;//默认UTF-8
            this.fileNameTB.Text = "";
        }

        private void AllBtn_Click(object sender, EventArgs e)
        {
            string rootPath = Directory.GetCurrentDirectory();
            //第一种方法
            string[] files = Directory.GetFiles(rootPath, "*.csv");

            foreach (string file in files)
            {
                if(convert(file)==false)
                {
                    return;
                }
            }
            MessageBox.Show("转换完成！");
        }

        private bool convert(string file)
        {
            Encoding encodeOld = Encoding.Default;
            try
            {
                encodeOld = EncodingType.GetType(file);
            }
            catch(IOException)
            {
                string Text = file.Substring(file.LastIndexOf("\\") + 1);
                MessageBox.Show("文件【" + Text+"】被其他软件打开了，请关闭后再转换！");
                return false;
            }
            string content = File.ReadAllText(file, encodeOld);

            string encodeName = this.encodeCb.Text;
            if(encodeName=="ANSI")
            {
                encodeName = "gb2312";
            }
            Encoding encode = Encoding.GetEncoding(encodeName);
            File.WriteAllText(file, content, encode);
            return true;
        }

        private void selectBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfiledialog = new OpenFileDialog();//声明并初始化openfiledialog类
            openfiledialog.InitialDirectory = Directory.GetCurrentDirectory();//设置文件打开初始目录为E盘
            openfiledialog.Title = "打开文本文件";//设置打开文件对话框标题
            openfiledialog.Filter = "csv Files(*.csv)|*.csv|txt Files(*.txt)|*.txt|All Files(*.*)|*.*";//设置文件过滤类型
            openfiledialog.FilterIndex = 1;//根据文件类型索引设置文件过滤类型
            openfiledialog.RestoreDirectory = true;//设置对话框是否记忆之前打开的目录
            if (openfiledialog.ShowDialog() == DialogResult.OK)//当点击文件对话框的确定按钮时打开相应的文件
            {                                                  //并执行如下语句块
                string filepath = openfiledialog.FileName;//获取选择文件的完整路径名（含文件名称）
                fileNameTB.Text = filepath.Substring(filepath.LastIndexOf("\\") + 1);

                convert(filepath);
                MessageBox.Show("转换完成！");
            }                                             //获取选择文件的完整文件名（不含路径）

        }


    }
}
